﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace BaseUi
{
    /// <summary>
    /// Ip和端口
    /// </summary>
    public class IpPort
    {
        /// <summary>
        /// Ip地址
        /// </summary>
        public string Address { get; set; }
        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; set; }

        [Newtonsoft.Json.JsonIgnore]
        public IPEndPoint IPEndPoint { get => new IPEndPoint(IPAddress.Parse(Address), Port); }

        public override string ToString()
        {
            return Port <= 0 ? Address : $"{Address}:{Port}";
        }
    }

    /// <summary>
    /// Ip和端口扩展
    /// </summary>
    public static class IpPortEx
    {
        /// <summary>
        /// 将字符串转为Ip和端口
        /// </summary>
        /// <param name="IpPortStr">Ip和端口字符串</param>
        /// <returns>Ip和端口</returns>
        public static IpPort ToIpPort(this string IpPortStr)
        {
            IpPortStr = IpPortStr?.Trim() ?? "";

            if (string.IsNullOrEmpty(IpPortStr))
                return new IpPort();

            var aaa = IpPortStr.Split(new char[] { ':', '：' }, StringSplitOptions.RemoveEmptyEntries);
            if (!aaa.Any())
                return new IpPort();
            else if (aaa.Length == 2)
                return new IpPort() { Address = aaa[0], Port = Convert.ToInt32(aaa[1]) };
            else if (aaa.Length == 1)
                if (aaa[0].Contains("."))
                    return new IpPort() { Address = aaa[0] };
                else
                    return new IpPort() { Address = "", Port = Convert.ToInt32(aaa[0]) };
            else
                return new IpPort();
        }
    }
}
